package com.iweb.dao.impl;

import com.iweb.dao.FoodDao;
import com.iweb.pojo.Food;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: jack
 * @date: 2022-08-05 0005
 * @ApiNOTE:
 */
public class FoodDaoImpl implements FoodDao {

  private DataSource dataSource;

  public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
  }

  @Override
  public List<Food> selectList() {
    List<Food> foods = new ArrayList<>();
    Connection conn = null;
    try {
      conn = dataSource.getConnection();
      PreparedStatement pst = conn.prepareStatement("select * from tb_food");
      ResultSet rs = pst.executeQuery();
      while (rs.next()) {
        Food food = new Food(
                rs.getInt(1),
                rs.getString(2),
                rs.getString(3),
                rs.getDouble(4),
                rs.getString(5),
                rs.getString(6),
                rs.getInt(7),
                rs.getInt(8)
        );

        foods.add(food);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }


    return foods;
  }
}
